var dirtle = require('dirtle');
var path = require('path');
var db = new dirtle(path.join(__dirname, 'db.json')).db;

function createTable(table) {
    if (db[table] == null) {
        db[table] = [];
        db[table + '_id'] = 0;
    } 
}
exports.createTable = createTable;

function insertItem(table, item) {
    // set item id
    item['id'] = db[table + '_id'];
    // increment id 
    db[table + '_id'] = db[table + '_id'] + 1;
    // save the item
    db[table].push(item);
}
exports.insertItem = insertItem;

function findItemById(table, id) {
    var itemArray = findAllItems(table);
    for (var i = 0; i < itemArray.length; i++) {
        if (itemArray[i].id == id) {
            return itemArray[i];
        }
    }
    return null;
}
exports.findItemById = findItemById;

function findAllItems(table) {
    var resultItemArray = [];
    var itemArray = db[table];
    for (var i = 0; i < itemArray.length; i++) {
        if (itemArray[i].id != -1) {
            resultItemArray.push(itemArray[i]);
        }
    }
    return resultItemArray;
}
exports.findAllItems = findAllItems;

function updateItem(table, item) {
    if (item.id != null) {
        var itemArray = findAllItems(table);
        for (var i = 0; i < itemArray.length; i++) {
            if (itemArray[i].id == item.id) {
                itemArray[i] = item;
            }
        }
    } else {
        console.log('WARN - item has no id ! ');
    }
}
exports.updateItem = updateItem; 

function removeItem(table, item) {
    if (item.id != null) {
        var itemArray = findAllItems(table);
        for (var i = 0; i < itemArray.length; i++) {
            if (itemArray[i].id == item.id) {
                itemArray[i] = { id: -1 };
            }
        }
    } else {
        console.log('WARN - item has no id ! ');
    }
}
exports.removeItem = removeItem;

function selectItems(table, fieldArray, valueArray) {
    var itemArray = findAllItems(table);
    var isSelected = true;
    var resultItemArray = [];
    for (var i = 0; i < itemArray.length; i++) {
        isSelected = true;
        for (var j = 0; j < fieldArray.length; j++) {
            if (itemArray[i][fieldArray[j]] != valueArray[j]) {
                isSelected = false;
                break;
            }
        }
        if (isSelected) {
            resultItemArray.push(itemArray[i]);
        }
    }
    return resultItemArray;
}
exports.selectItems = selectItems;
